package com.zhj.lock;

import com.zhj.bean.LockRecord;
import com.zhj.mapper.LockRecordMapper;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author zhj
 */
@Component
public class DBLock implements Lock {

    private static final String LOCK_NAME = "db_lock_stock";
    @Resource
    private LockRecordMapper lockRecordMapper;

    @Override
    public void lock() {
        while (true) {
            boolean flag = tryLock();
            if (flag) {
                try {
                    LockRecord lockRecord = new LockRecord();
                    lockRecord.setLockName(LOCK_NAME);
                    lockRecordMapper.insert(lockRecord);
                    return;
                } catch (Exception e) {
                    System.out.println("-------");
                }
            } else {
                System.out.println("等待中...");
            }
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    /**
     * 尝试获取锁，根据指定的名称在数据表发起一次查询
     * @return
     */
    @Override
    public boolean tryLock() {
        Example example = new Example(LockRecord.class);
        example.createCriteria().andEqualTo("lockName", LOCK_NAME);
        LockRecord lockRecord = lockRecordMapper.selectOneByExample(example);
        if (lockRecord == null) {
            return true;
        }
        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        Example example = new Example(LockRecord.class);
        example.createCriteria().andEqualTo("lockName", LOCK_NAME);
        lockRecordMapper.deleteByExample(example);
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
